<template>
	<wd-tabs v-model="tab">
	    <wd-tab title="列表">
	      <view class="content">
			  <view style="padding: 10px 0;position: sticky;z-index: 99;top: 40px;background: #f1f1f1">
				  <!-- 顶部切换标签 -->
				  <view class="tab-container">
					  <text :class="{'active-tab': currentTab === 0}" @click="changeTab(0)">当前报警</text>
					  <text :class="{'active-tab': currentTab === 1}" @click="changeTab(1)">历史报警</text>
				  </view>
				  <!-- 搜索框 -->
				  <view class="search-container">
					  <input type="text" class="search-input" v-model="searchText" placeholder="请输入设备名称" />
					  <button class="search-button" @click="searchAlerts()">搜索</button>
				  </view>
			  </view>
			<view class="container">
				<!-- 报警记录列表 -->
				<view class="alert-list" v-if="currentTab===0">
				  <view class="alert-list" v-for="alert in noDealTableData" :key="alert.id">
					<view class="alert-item">
					  <!-- 上部内容：左侧图标和右侧设备信息 -->
					  <view class="alert-top">
						<!-- 左侧图标 -->
						<view class="alert-left">
						  <view class="iconfont alert-icon" v-if="alert.isDeal===0">&#xe68e;</view>
						  <view class="iconfont deal-alert-icon" v-if="alert.isDeal===1">&#xe68e;</view>
						</view>

						<!-- 右侧设备信息 -->
						<view class="alert-right">
						  <!-- 第一行：设备名称和设备号 -->
						  <view class="alert-info">
							<text class="device-name">{{ alert.equipmentName }}</text>
							<text class="device-id">{{ alert.equipmentId }}</text>
						  </view>
						  <!-- 第二行：报警描述 -->
						  <text class="alert-desc" v-if="alert.isDeal===0">{{ alert.warnAddr }}发生报警，请及时处理</text>
						  <text class="alert-desc" v-if="alert.isDeal===1">{{ alert.warnAddr }}发生报警，已处理</text>
						  <!-- 第三行：报警时间 -->
						  <text class="alert-time">{{ alert.warnTime }}</text>
						</view>
					  </view>

					  <!-- 分割线 -->
					  <view class="divider"></view>

					  <!-- 底部内容：操作按钮 -->
					  <view class="alert-actions">
						<button class="action-button" v-if="alert.teleNotification === '0' && alert.faultReport === '0' && alert.fieldSurvey === '0' && alert.eliminHidDang === '0'"
								type="primary" size="small" icon="Edit" @click="updateState(alert)">通知</button>
						  <button class="action-button" v-if="alert.teleNotification === '1' && alert.faultReport === '0' && alert.fieldSurvey === '0' && alert.eliminHidDang === '0'"
								  type="primary" size="small" icon="Edit" @click="updateState(alert)">上报</button>
						  <button class="action-button" v-if="alert.teleNotification === '1' && alert.faultReport === '1' && alert.fieldSurvey === '0' && alert.eliminHidDang === '0'"
								  type="primary" size="small" icon="Edit" @click="updateState(alert)">勘查</button>
						  <button class="action-button" v-if="alert.teleNotification === '1' && alert.faultReport === '1' && alert.fieldSurvey === '1' && alert.eliminHidDang === '0'"
								  type="primary" size="small" icon="Edit" @click="updateState(alert)">排除</button>
						  <button class="action-button" v-if="alert.isMisinformation === '0'" @click="submitAlert(alert)">真实</button>
						  <button class="action-button" v-if="alert.isMisinformation === '1'" @click="submitAlert(alert)">误报</button>
						<button class="action-button" @click="detialClick(alert)">详情</button>
					  </view>
					</view>
				  </view>
				</view>
				<!-- 报警记录列表 -->
				<view class="alert-list" v-if="currentTab===1">
					<view class="alert-list" v-for="alert in tableData" :key="alert.id">
						<view class="alert-item">
							<!-- 上部内容：左侧图标和右侧设备信息 -->
							<view class="alert-top">
								<!-- 左侧图标 -->
								<view class="alert-left">
									<view class="iconfont alert-icon" v-if="alert.isDeal===0">&#xe68e;</view>
									<view class="iconfont deal-alert-icon" v-if="alert.isDeal===1">&#xe68e;</view>
								</view>

								<!-- 右侧设备信息 -->
								<view class="alert-right">
									<!-- 第一行：设备名称和设备号 -->
									<view class="alert-info">
										<text class="device-name">{{ alert.equipmentName }}</text>
										<text class="device-id">{{ alert.equipmentId }}</text>
									</view>
									<!-- 第二行：报警描述 -->
									<text class="alert-desc" v-if="alert.isDeal===0">{{ alert.warnAddr }}发生报警，请及时处理</text>
									<text class="alert-desc" v-if="alert.isDeal===1">{{ alert.warnAddr }}发生报警，已处理</text>
									<!-- 第三行：报警时间 -->
									<text class="alert-time">{{ alert.warnTime }}</text>
								</view>
							</view>

							<!-- 分割线 -->
							<view class="divider"></view>

							<!-- 底部内容：操作按钮 -->
							<view class="alert-actions">
								<button class="action-button" v-if="alert.teleNotification === '0' && alert.faultReport === '0' && alert.fieldSurvey === '0' && alert.eliminHidDang === '0'"
										type="primary" size="small" icon="Edit" @click="updateState(alert)">通知</button>
								<button class="action-button" v-if="alert.teleNotification === '1' && alert.faultReport === '0' && alert.fieldSurvey === '0' && alert.eliminHidDang === '0'"
										type="primary" size="small" icon="Edit" @click="updateState(alert)">上报</button>
								<button class="action-button" v-if="alert.teleNotification === '1' && alert.faultReport === '1' && alert.fieldSurvey === '0' && alert.eliminHidDang === '0'"
										type="primary" size="small" icon="Edit" @click="updateState(alert)">勘查</button>
								<button class="action-button" v-if="alert.teleNotification === '1' && alert.faultReport === '1' && alert.fieldSurvey === '1' && alert.eliminHidDang === '0'"
										type="primary" size="small" icon="Edit" @click="updateState(alert)">排除</button>
								<button class="action-button" v-if="alert.isMisinformation === '0'" @click="submitAlert(alert)">真实</button>
								<button class="action-button" v-if="alert.isMisinformation === '1'" @click="submitAlert(alert)">误报</button>
								<button class="action-button" @click="detialClick(alert)">详情</button>
							</view>
						</view>
					</view>
				</view>
			  </view>
		  </view>
	    </wd-tab>
		<wd-tab title="概览">
		  <view class="content padding">
			  <view class="card">
			    <view class="card-title">当前报警统计</view>
			    <view class="charts">
					<canvas ref="charts" class="charts" canvas-id="kVcPKZfPWVQunWGotlYtzpfyKNkIKkAy" id="kVcPKZfPWVQunWGotlYtzpfyKNkIKkAy" @touchend="tap"/>
			    </view>
			  </view>
		  </view>
		</wd-tab>
	</wd-tabs>

</template>

<script>
import uCharts from "../../node_modules/@qiun/ucharts/u-charts.js"
import request from '@/util/request';
var uChartsInstance = [];
export default {
  data() {
    return {
		triggered:false,
		pageNum:1,
		pageSize:10,
	  cWidth: 750,
	  cHeight: 500,
	  startX: 0,
	  tab:1,
      currentTab: 0,
	  total: 0,
	  tableData: [],
	  noDealTableData: [],
	  searchText: '', // 搜索关键词
    };
  },
    mounted() {
  	  this.load();
  	  this.noDealLoad();
      //这里的 750 对应 css .charts 的 width
      this.cWidth = uni.upx2px(680);
      //这里的 500 对应 css .charts 的 height
      this.cHeight = uni.upx2px(500);
      this.getServerData();
    },
	onPullDownRefresh() {
		// 列表
		if(this.tab==0){
			this.pageNum=1;
			this.pageSize=20;
			this.searchAlerts()
		}else {// 概况
			this.getServerData()
		}
		uni.stopPullDownRefresh();
	},
	onReachBottom() { //触底事件
		if (this.pageNum * this.pageSize >= this.total) {
			uni.showToast({
				title: '没有更多数据了',
				icon: 'none',
				duration: 1000
			});
		} else {
			uni.showLoading({
				title: '加载中'
			});
			this.pageSize+=10
			this.searchAlerts()
			setTimeout(() => {
				uni.hideLoading()
			}, 500)
		}
	},
  methods: {
    changeTab(index) {
		this.pageNum=1
		this.pageSize=10
		if(this.currentTab==index)return
      this.currentTab = index;
	  this.searchText=""
	  this.searchAlerts()
    },
    // 处理逻辑
	updateState(alert) {
		if(alert.teleNotification === '1' && alert.faultReport === '0' && alert.fieldSurvey === '0' && alert.eliminHidDang === '0'){
			uni.navigateTo({
				url:"/pages/warn/faultHandler"+"?data="+JSON.stringify(alert)
			})
		} else if (alert.teleNotification === '1' && alert.faultReport === '1' && alert.fieldSurvey === '0' && alert.eliminHidDang === '0') {
			uni.navigateTo({
				url:"/pages/warn/fieldHandler"+"?data="+JSON.stringify(alert)
			})
		} else if (alert.teleNotification === '1' && alert.faultReport === '1' && alert.fieldSurvey === '1' && alert.eliminHidDang === '0') {
			uni.navigateTo({
				url:"/pages/warn/eliminHandler"+"?data="+JSON.stringify(alert)
			})
		}
    },
	submitAlert(alert) {
	  uni.navigateTo({
		  url:"/pages/warn/misinHandler"+"?data="+JSON.stringify(alert)
	  })
	},
    // 详情逻辑
    detialClick(item) {
		uni.navigateTo({
			url:"/pages/warn/detial"+"?data="+JSON.stringify(item)
		})
    },
	searchAlerts(){
		if(this.currentTab===0){
			this.noDealLoad()
		}else if(this.currentTab===1){
			this.load()
		}
	},

	load() {
	  let level = this.$store.state.userInfo.level;
	  let organizationId = this.$store.state.userInfo.organization;
	  let isAllClient = this.$store.state.userInfo.isAllClient;
	  let clientIds;
	  if (isAllClient === "1") {
		  clientIds = this.$store.state.userInfo.clientIds;
	  } else {
		  clientIds = [];
	  }
	  request.get("/warn-record/page?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize +"&equipmentName="+ this.searchText + "&organizationId=" + organizationId +
			  "&level=" + level + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
		  if (res.code === '200') {
			  for (let key in res.data) {
				  if (key === "record") {
					  this.tableData = res.data[key];
				  } else if (key === "total") {
					  this.total = res.data[key];
				  }
			  }
		  }
	  })
	},
	noDealLoad() {
	  let level = this.$store.state.userInfo.level;
	  let organizationId = this.$store.state.userInfo.organization;
	  let isAllClient = this.$store.state.userInfo.isAllClient;
	  let clientIds;
	  if (isAllClient === "1") {
		  clientIds = this.$store.state.userInfo.clientIds;
	  } else {
		  clientIds = [];
	  }
	  request.get("/warn-record/page?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize +"&equipmentName="+ this.searchText +"&isDeal="+ 0 + "&organizationId=" + organizationId +
			  "&level=" + level + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
		  if (res.code === '200') {
			  for (let key in res.data) {
				  if (key === "record") {
					  this.noDealTableData = res.data[key];
				  } else if (key === "total") {
					  this.total = res.data[key];
				  }
			  }
		  }
	  })
	},
	getServerData() {
		let level = this.$store.state.userInfo.level;
		let organizationId = this.$store.state.userInfo.organization;
		let isAllClient = this.$store.state.userInfo.isAllClient;
		let clientIds;
		if (isAllClient === "1") {
			clientIds = this.$store.state.userInfo.clientIds;
		} else {
			clientIds = [];
		}
		request.get("/warn-record/getCountByState?organizationId=" + organizationId +
				"&level=" + level + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
			if (res.code === '200') {
				let fireCount = 0;
				let breakCount = 0;
				if(res.data.length > 0) {
					for (let i = 0; i < res.data.length; i++) {
						if(res.data[i].state === '1'){
							fireCount = res.data[i].count
						} else if (res.data[i].state === '2') {
							breakCount = res.data[i].count
						}
					}
				}
				//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
				let data = {
					series: [
						{
							data: [{"name":"报警",
									"value":fireCount
									},
									{"name":"故障",
									 "value":breakCount
									}]
						}
					]
				};
				this.drawCharts('kVcPKZfPWVQunWGotlYtzpfyKNkIKkAy', data);
			}
		})
	    },
	     drawCharts(id,data){
	          const ctx = uni.createCanvasContext(id, this);
	          uChartsInstance[id] = new uCharts({
	            type: "ring",
	            context: ctx,
	            width: this.cWidth,
	            height: this.cHeight,
	            series: data.series,
	            animation: true,
	            rotate: false,
	            rotateLock: false,
	            background: "#FFFFFF",
				color: ["#EE6666","#FAC858","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
	            padding: [5,5,5,5],
	            dataLabel: true,
	            enableScroll: false,
	            legend: {
	              show: true,
	              position: "top",
	              lineHeight: 25
	            },
	            extra: {
	              ring: {
	                ringWidth: 50,
	                activeOpacity: 0.5,
	                activeRadius: 10,
	                offsetAngle: 0,
	                labelWidth: 15,
	                border: true,
	                borderWidth: 3,
	                borderColor: "#FFFFFF"
	              }
	            }
	          });
	        },
	    tap(e){
	      uChartsInstance[e.target.id].touchLegend(e);
	      uChartsInstance[e.target.id].showToolTip(e);
	    }
  }
};
</script>

<style scoped>
.container {
  padding: 0 20rpx 20rpx 20rpx;
}
:deep(.is-active){
	color: var(--blue-color);
}
:deep(.wd-tabs__nav){
	position: sticky;
	z-index: 90;
	top: 0;
}
:deep(.wd-tabs__container){
	overflow: visible;
}
:deep(.wd-tabs__line){
	width:20%;
	background: var(--blue-color);
}

.content {
	background-color: var(--bg-color);
}

.tab-container {
  display: flex;
  justify-content: space-around;
  background-color: #f8f8f8;
  padding: 10px 0;
}

.active-tab {
  color: #007aff;
  font-weight: bold;
}

.alert-list {
  margin-top: 10rpx;
}

.alert-item {
  background-color: #fff;
  padding: 20rpx;
  margin: 10rpx 0;
  border-radius: 10rpx;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 上部：左右结构 */
.alert-top {
  display: flex;
  align-items: center;
}

.alert-left {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.alert-icon {
  color: #ff0000;
  font-size: 40px;
}

.deal-alert-icon {
	color: #007aff;
	font-size: 40px;
}
.search-container {
  margin: 10px 10px 0 10px;
  height: 40px;
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 10rpx;
}

.search-input {
  flex: 1;
  height: 40px;
  font-size: 16px;
  padding: 0 10px;
  border: 1px solid #ddd;
  border-radius: 5rpx;
}

.search-button {
  margin-left: 10rpx;
  height: 40px;
  line-height: 40px;
  font-size: 16px;
  color: #fff;
  background-color: var(--blue-color);
  border-radius: 5rpx;
}

.alert-right {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 第一行：设备名称和设备号 */
.alert-info {
  display: flex;
  justify-content: space-between;
}

.device-name {
  font-size: 20px;
  color: #333;
  font-weight: bold;
}

.device-id {
  font-size: 15px;
  color: #555;
}

/* 第二行：报警描述 */
.alert-desc {
  color: #989898;
  font-size: 14px;
  margin: 5rpx 0;
}

/* 第三行：报警时间 */
.alert-time {
  font-size: 18px;
  margin-top: 4rpx;
}

/* 分割线样式 */
.divider {
  height: 1px;
  background-color: #e0e0e0;
  margin: 10px 30px;
}

/* 底部操作按钮样式 */
.alert-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10rpx;
}
:deep(uni-button){
	line-height:1.9
}

.action-button {
  background-color: var(--blue-color);
  color: #fff;
  border-radius: 5rpx;
  font-size: 16px;
}
.card {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15rpx;
  color: #333;
}

.charts {
  width: 100%;
  height: 300px;
}

</style>
